import _ from 'lodash';
import { observable, toJS } from 'mobx';
import { ListViewPage } from 'weaver-mobile-page';

export default class ListViewStore {
  list = new ListViewPage.Store({});
  opts = {};

  clearData = this.list.clearData
  
  constructor(opts = {}) {
    this.opts = _.extend({ 
      isTable: false,
      // 数据重新加载不会显示首次加载的loading，故增加属性来控制loading的显示
      enableFullLoading: true,
    }, opts);

    const getData = this.list.getData;

    if (this.opts.enableFullLoading) {
      this.list.fullLoading = observable.box(false);
    }

    this.list.getData = (params, callback, fullLoading = false) => {
      return getData(params, (dataRes) => {
        // hack处理，ListViewPage.Store内isTable会根据后端返回的mobileshowtemplate来赋值
        dataRes.mobileshowtemplate = this.opts.isTable;
        
        if (_.isFunction(callback)) {
          callback(dataRes);
        }
      }, fullLoading);
    };
  }

  getData(getDataKey, fullLoading = true) {
    if (fullLoading) {
      this.list.current = 1;
      this.toggleFullLoading(true);
    }

    return new Promise(res => {
      getDataKey().then(dataKey => {
        this.list.getData({ dataKey }, () => {
          fullLoading && this.toggleFullLoading(false);
          res();
        }, fullLoading);
      });
    });
  }

  toggleFullLoading(value) {
    if (this.opts.enableFullLoading) {
      this.list.fullLoading.set(value);
    }
  }

  updateDataSource(map) {
    const datas = toJS(this.list.data);

    this.list.data = map(datas);
    this.list.updateDataSource();
  }
}